import { Component, OnInit, ViewChild } from '@angular/core';
import { Http } from '@angular/http';
import { ModalDirective } from 'ngx-bootstrap/modal';
import { ConfigService } from '../../../core/common/config.service';
import swal from 'sweetalert2';
import { SelectComponent } from '../../../shared/component/ng2-select/select';
import { CommonService } from '../../../core/common/common.service';
import { Params, ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-usermanage',
  templateUrl: './usermanage.component.html',
  styleUrls: ['./usermanage.component.scss']
})
export class UsermanageComponent implements OnInit {
  @ViewChild('editAccountModal') public editAccountModal: ModalDirective;
  @ViewChild('editGroupModal') public editGroupModal: ModalDirective;
  @ViewChild('accUserType') public accUserType: SelectComponent;
  @ViewChild('accountSubmit') public accountSubmit;
  @ViewChild('accountInput') public accountInput;
  @ViewChild('accGroup') public accGroup: SelectComponent;
  @ViewChild('chnlLists') public chnlLists;
  @ViewChild('accEmail') public accEmail;
  private chnlId: string = null;
  // 新建和编辑界面的信息切换
  public displayMsg: any = {
    // header: '',
    // confirmBtn: ''
  };
  // 表格中展示的信息
  public tabledatas: any = {
    tableInfo: [],
    childAccountInfo: []
  };
  // 渠道分组信息
  public chnlGroupInfo: any = {
    chnl: '',
    chnlChilds: []
  };
  // 分组的参数
  public groupInfo: any = {
    // 当前账号的权限
    chnlLevel: '',
    // 新建分组名称
    groupName: '',
    // 登录账号所属的渠道信息
    chnlId: '',
    chnlName: '',
    // 当前分组参数
    editName: '',
    editId: '',
    // 弹窗（新建或者编辑）分组的条件
    newOrEdit: '',
    // 是否展开渠道分组
    isOpen: true
  };
  // 新建/编辑账号表格中的信息
  public editAccountInfo: any = {
    topGroup: '',
    group: '',
    account: '',
    name: '',
    email: '',
    mobile: '',
    telephone: '',
    remark: '',
    userType: '',
    newOrEdit: '',
    userId: ''
  };
  // 表单验证格式错误提示
  public regularForm: any = {
    account: true,
    email: true
  };
  // 分页配置
  public config: any = {
    paging: true,
    itemsPerPage: 8,
    length: '',
    page: 1,
    maxSize: 5,
    firstText: '|<',
    previousText: '<<',
    nextText: '>>',
    lastText: '>|'
  };
  private initParameters(): void {
    this.route.params.switchMap((params: Params) => {
      const result: any = [];
      if (params['chnlId']) {
        this.chnlId = params['chnlId'];
      }
      return result;
    }
    ).subscribe((c: any) => { });
  }
  // 获取渠道下的分组信息
  public getChnlGroup() {
    try {
      const param = this.chnlId ? { 'chnlId': this.chnlId } : null;
      const chnlGroup_url = this.configService.get('url') + '?service=ChnlService&method=getChnlGroupList';
      this.http.post(chnlGroup_url, param).toPromise().then((data: any) => {
        const dataInfo = data.json();
        const selectInfo: any[] = [];
        if (dataInfo.code === '0000') {
          this.chnlGroupInfo.chnl = dataInfo.info[0];
          // 当前账号的权限
          this.groupInfo.chnlLevel = this.chnlGroupInfo.chnl.chnlLevel;
          // this.userType();
          this.chnlGroupInfo.chnlChilds = dataInfo.info.slice(1);
          $(this.chnlLists.nativeElement).children('li:first').addClass('active');
          dataInfo.info.forEach(value => {
            selectInfo.push({ id: value.chnlId, text: value.chnlName });
          });
          this.accGroup.items = selectInfo;
          this.groupInfo.chnlName = this.groupInfo.editName = dataInfo.info[0].chnlName;
          this.groupInfo.chnlId = this.groupInfo.editId = dataInfo.info[0].chnlId;
          this.getChnlMember(this.groupInfo.chnlId);
        } else {
          console.log(dataInfo.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  }
  // 获取权限列表
  public userType() {
    try {
      const userType_url = this.configService.get('url') + '?service=TableDictService&method=getDictList';
      this.http.post(userType_url, { 'code': 'USER_TYPE_2' }).toPromise().then((data: any) => {
        const dataInfo = data.json();
        const selectInfo: any[] = [];
        if (dataInfo.code === '0000') {
          dataInfo.info.forEach(value => {
            selectInfo.push({ id: value.value, text: value.label });
          });
          this.accUserType.items = selectInfo;
        } else {
          console.log(dataInfo.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  }
  // 弹出新建和编辑分组窗口
  public showEditGroup(msg) {
    // if (msg === 'edit' && this.groupInfo.chnlId === this.groupInfo.editId) {
    //   swal('请选择渠道以外的分组!', '', 'error').catch(swal.noop);
    // } else {
    //   if (msg === 'new') {

    //     if (this.groupInfo.chnlId !== this.groupInfo.editId) {
    //       swal('请选择渠道' + this.groupInfo.chnlName + '后,再创建分组!', '', 'error').catch(swal.noop);
    //     }
    //     this.displayMsg = {
    //       header: '添加分组',
    //       confirmBtn: '添加'
    //     };
    //     this.groupInfo.groupName = '';
    //     // return;
    //   } else {
    //     this.displayMsg = {
    //       header: '修改分组',
    //       confirmBtn: '修改'
    //     };
    //     this.groupInfo.groupName = this.groupInfo.editName;
    //   }
    //   this.groupInfo.newOrEdit = msg;
    //   this.editGroupModal.show();
    // }
    if (msg === 'new') {
      if (this.groupInfo.chnlId !== this.groupInfo.editId) {
        swal('提示', '只允许在渠道下创建分组，请先选择渠道--' + this.groupInfo.chnlName, 'warning').catch(swal.noop);
        return;
      } else {
        this.displayMsg = {
          header: '添加分组',
          confirmBtn: '添加'
        };
        this.groupInfo.groupName = '';
      }
    } else {
      if (this.groupInfo.chnlId === this.groupInfo.editId) {
        swal('提示', '请选择渠道以外的分组!', 'warning').catch(swal.noop);
        return;
      } else {
        this.displayMsg = {
          header: '修改分组',
          confirmBtn: '修改'
        };
        this.groupInfo.groupName = this.groupInfo.editName;
      }
    }
    this.groupInfo.newOrEdit = msg;
    this.editGroupModal.show();
  };
  // 创建分组功能
  public createGroup() {
    try {
      const createGroup_url = this.configService.get('url') + '?service=ChnlService&method=insertChnl';
      this.http.post(createGroup_url, {
        'parentId': this.groupInfo.chnlId,
        'chnlName': this.groupInfo.groupName
      }).toPromise().then((data: any) => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          this.getChnlGroup();
          this.editGroupModal.hide();
        } else {
          swal('失败', dataInfo.message, 'error').catch(swal.noop);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  }
  // 编辑分组功能
  public editGroups() {
    try {
      const editGroup_url = this.configService.get('url') + '?service=ChnlService&method=updateChnl';
      this.http.post(editGroup_url, {
        'chnlId': this.groupInfo.editId,
        'chnlName': this.groupInfo.groupName
      }).toPromise().then((data: any) => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          $(this.chnlLists.nativeElement).find('#' + this.groupInfo.editId).text(this.groupInfo.groupName);
          this.groupInfo.editName = this.groupInfo.groupName;
          this.editGroupModal.hide();
        } else {
          swal('失败', dataInfo.message, 'error').catch(swal.noop);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  };
  // 删除分组
  public deleteGroup() {
    if (this.groupInfo.chnlId === this.groupInfo.editId) {
      swal('提示', '请选择渠道以外的分组!', 'warning').catch(swal.noop);
    } else {
      if (this.tabledatas.childAccountInfo.length > 0) {
        swal('提示', '请先移除分组下的账号!', 'warning').catch(swal.noop);
      } else {
        try {
          const editGroup_url = this.configService.get('url') + '?service=ChnlService&method=deleteChnl';
          this.http.post(editGroup_url, { 'chnlId': this.groupInfo.editId }).toPromise().then((data: any) => {
            const dataInfo = data.json();
            if (dataInfo.code === '0000') {
              this.getChnlGroup();
              this.editGroupModal.hide();
            } else {
              swal('失败', dataInfo.message, 'error').catch(swal.noop);
            }
          });
        } catch (e) {
          // TODO handle exception
        };
      }
    }
  }
  // 点击分组获取对应的分组ID，通过ID请求分组内的成员信息
  public chnlSelect(target) {
    if ($(target).get(0).tagName === 'B') {
      if ($(target).hasClass('glyphicon-chevron-down')) {
        $(target).removeClass('glyphicon-chevron-down').addClass('glyphicon-chevron-right');
        this.groupInfo.isOpen = false;
      } else {
        $(target).removeClass('glyphicon-chevron-right').addClass('glyphicon-chevron-down');
        this.groupInfo.isOpen = true;
      }
    } else {
      $(this.chnlLists.nativeElement).find('li').removeClass('active');
      $(target).addClass('active');
      const curId = $(target).attr('id');
      this.groupInfo.editName = $.trim($(target).text());
      this.groupInfo.editId = curId;
      this.getChnlMember(curId);
    }
  }
  // 通过分组ID获取分组下的人员
  public getChnlMember(id) {
    // 初始化表格内容
    this.tabledatas.childAccountInfo = [];
    try {
      const chnlMember_url = this.configService.get('url') + '?service=SaleService&method=getChnlSales';
      this.http.post(chnlMember_url, { 'chnlId': id }).toPromise().then((data: any) => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          this.tabledatas.tableInfo = dataInfo.info;
          this.config.length = this.tabledatas.tableInfo.length;
          this.pageChanged(this.config);
        } else {
          console.log(dataInfo.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  }
  // 分页功能
  public pageChanged(event) {
    this.tabledatas.childAccountInfo = this.tabledatas.tableInfo.slice((event.page - 1) * this.config.itemsPerPage, event.page * this.config.itemsPerPage);
  }
  // 弹出新建或编辑账号窗口
  public showEditAccount(msg) {
    $.each(this.editAccountInfo, (key) => {
      this.editAccountInfo[key] = '';
    });
    this.regularForm.account = true;
    this.regularForm.email = true;
    if (msg === 'new') {
      this.editAccountInfo.newOrEdit = 'new';
      this.displayMsg = {
        header: '添加账号',
        confirmBtn: '添加'
      };
      if (this.groupInfo.chnlLevel !== '1') {
        this.editAccountInfo.userType = '5';
      }
      this.editAccountModal.show();
    } else {
      this.editAccountInfo.newOrEdit = 'edit';
      this.displayMsg = {
        header: '编辑账号',
        confirmBtn: '修改'
      };
      const accountInfo = this.getAccountChecked();
      if (accountInfo.length === 1) {
        this.tabledatas.childAccountInfo.forEach((value) => {
          if (value.account === accountInfo[0].account) {
            this.editAccountInfo.userId = value.userId;
            $.each(value, (key) => {
              this.editAccountInfo[key] = value[key];
            });
          }
        });
        this.editAccountInfo.topGroup = this.groupInfo.chnlName;
        this.editAccountInfo.group = this.groupInfo.editId;
        this.editAccountModal.show();
      } else {
        swal('提示', '请选择其中一个账号进行编辑', 'warning').catch(swal.noop);
      }
    }
  }
  // 新建或编辑账号信息
  public editAccount(msg) {
    let editUser_url = '';
    const updataInfo: any = {
      'account': this.editAccountInfo.account,
      'name': this.editAccountInfo.name,
      'email': this.editAccountInfo.email,
      'mobile': this.editAccountInfo.mobile,
      'telephone': this.editAccountInfo.telephone,
      'remark': this.editAccountInfo.remark,
      'userType': this.editAccountInfo.userType,
      'chnlId': this.groupInfo.editId
    };
    if (msg === 'new') {
      editUser_url = this.configService.get('url') + '?service=UserService&method=addUser';
    } else {
      editUser_url = this.configService.get('url') + '?service=UserService&method=updateUserInfo';
      updataInfo.userId = this.editAccountInfo.userId;
      if (this.groupInfo.editId !== this.editAccountInfo.group) {
        updataInfo.chnlId = this.editAccountInfo.group;
        updataInfo.oldChnlId = this.groupInfo.editId;
      }
    }
    try {
      this.http.post(editUser_url, updataInfo).toPromise().then((data: any) => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          this.editAccountModal.hide();
          this.getChnlMember(this.groupInfo.editId);
        } else {
          swal('失败', dataInfo.message, 'error').catch(swal.noop);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  }
  // 激活或者冻结选中的账号
  public activateAccount(msg) {
    const accountInfo = this.getAccountChecked();
    if (accountInfo.length > 0) {
      try {
        const activateAccount_url = this.configService.get('url') + '?service=UserService&method=changeUserState';
        this.http.post(activateAccount_url, { 'action': msg, 'userIds': accountInfo }).toPromise().then((data: any) => {
          const dataInfo = data.json();
          if (dataInfo.code === '0000') {
            this.getChnlMember(this.groupInfo.editId);
          } else {
            swal('失败', dataInfo.message, 'error').catch(swal.noop);
          }
        });
      } catch (e) {
        // TODO handle exception
      };
    } else {
      swal('提示', '请选择至少一个账号进行操作', 'warning').catch(swal.noop);
    }
  }
  // 删除账号
  public destoryAccount() {
    const accountInfo = this.getAccountChecked();
    if (accountInfo.length === 1) {
      try {
        const destoryAccount_url = this.configService.get('url') + '?service=UserService&method=DestoryUser';
        this.http.post(destoryAccount_url, { 'userId': accountInfo[0].userId }).toPromise().then((data: any) => {
          const dataInfo = data.json();
          if (dataInfo.code === '0000') {
            this.getChnlMember(this.groupInfo.editId);
          } else {
            swal('失败', dataInfo.message, 'error').catch(swal.noop);
          }
        });
      } catch (e) {
        // TODO handle exception
      };
    } else {
      swal('提示', '请选择其中一个账号进行操作', 'warning').catch(swal.noop);
    }
  }
  // 重置账号密码
  public resetPwd() {
    const accountInfo = this.getAccountChecked();
    if (accountInfo.length === 1) {
      try {
        const resetPwd_url = this.configService.get('url') + '?service=UserService&method=resetUserPwd';
        this.http.post(resetPwd_url, { 'account': accountInfo[0].account }).toPromise().then((data: any) => {
          const dataInfo = data.json();
          if (dataInfo.code === '0000') {
            swal('密码重置成功', '', 'success').catch(swal.noop);
          } else {
            swal('警告', dataInfo.message, 'warning').catch(swal.noop);
          }
        });
      } catch (e) {
        // TODO handle exception
      };
    } else {
      swal('提示', '请选择其中一个账号进行操作', 'warning').catch(swal.noop);
    }
  }

  constructor(private route: ActivatedRoute, private http: Http, public configService: ConfigService, public commonService: CommonService) {
    this.initParameters();
    // 渠道分组信息
    this.getChnlGroup();
    // 获取权限列表
    this.userType();
  }
  ngOnInit() {
  }

  // 获取当前表格中被选中的账号信息
  public getAccountChecked() {
    return $(this.accountInput.nativeElement).find(':checked').map(function () {
      return { account: $(this).val(), userId: $(this).attr('id') };
    }).get();
  }
  // 判断账号是否已存在
  public existAccount(msg) {
    try {
      const existAccount_url = this.configService.get('url') + '?service=UserService&method=checkUserName';
      this.http.post(existAccount_url, { 'account': msg }).toPromise().then((data: any) => {
        const dataInfo = data.json();
        if (dataInfo.code === '0000') {
          if (dataInfo.info === true) {
            this.regularForm.account = true;
          } else {
            this.regularForm.account = false;
          }
        } else {
          console.log(dataInfo.message);
        }
      });
    } catch (e) {
      // TODO handle exception
    };
  }
  // 对邮件的格式进行验证
  public regularInput(info) {
    if (info === 'accEmail') {
      const re = /^(\w-*\.*)+@(\w-?)+(\.\w{2,})+$/;
      if (re.test(this.editAccountInfo.email)) {
        this.regularForm.email = true;
      } else {
        this.regularForm.email = false;
      }
    }
  }
  // 对输入的参数类型进行实时判断判断
  public regularType(name, value) {
    if (name === 'account') {
      return value.replace(/[^\w]/g, '');
    } else if (name === 'accMobile') {
      return value.replace(/[^\d+-]/g, '');
    }
  }
}
